#include <QPainter>
#include <QDebug>
#include <QMouseEvent>
#include <QColorDialog>
#include <QMenu>
#include "ColorChooser.h"

ColorChooser::ColorChooser(QWidget *parent) :
    QWidget(parent),
    _color(Qt::transparent),
    _oldColor(Qt::transparent),
    _colorSetted(false)
{
    setMinimumSize(40, 10);
}

void ColorChooser::paintEvent(QPaintEvent *)
{
    QPainter paint(this);
    paint.setBrush(_color);
    paint.drawRect(rect().adjusted(0, 0, -1, -1));

    QColor txtColor = _color.red() + _color.green() + _color.blue() < 380 ? Qt::white : Qt::black;
    paint.setPen(txtColor);
    if (_color == Qt::transparent)
        paint.drawText(rect(), "None", Qt::AlignHCenter | Qt::AlignVCenter);
    else
        paint.drawText(rect(), _color.name(), Qt::AlignHCenter | Qt::AlignVCenter);
}

void ColorChooser::setColor(QColor color)
{
    _color = color;
    if (!_colorSetted){
        _colorSetted = true;
        _oldColor = color;
    }
    update();
}

QColor ColorChooser::color()
{
    return _color;
}

void ColorChooser::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton){
        QColorDialog dial(_color);
        if (dial.exec() == QDialog::Accepted){
            _color = dial.selectedColor();
            update();
        }
    }
    if (event->button() == Qt::RightButton){
        QMenu * menu = new QMenu(this);

        QAction *act1 = new QAction(tr("Reset"), this);
        connect(act1, SIGNAL(triggered()), SLOT(colorReset()));
        act1->setEnabled(_color != _oldColor);
        menu->addAction(act1);

        QAction *act2 = new QAction(tr("To transparent"), this);
        connect(act2, SIGNAL(triggered()), SLOT(colorTransparent()));
        act2->setEnabled(_color != Qt::transparent);
        menu->addAction(act2);

        menu->popup(event->globalPos());
    }
}

void ColorChooser::colorReset()
{
    setColor(_oldColor);
}

void ColorChooser::colorTransparent()
{
    setColor(Qt::transparent);
}

